//
//  ZMYLKDB.m
//  奇阅
//
//  Created by 奇阅科技 on 14-10-21.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYLKDB.h"
#import "Config.h"
#import "LKDBHelper.h"
#import "SIDownloadManager.h"
#import "SIBreakpointsDownload.h"
#import "TaskList.h"
@interface ZMYLKDB()
{
    LKDBHelper *lkdb;
}
@end
@implementation ZMYLKDB
#pragma mark - 创建数据库
+(ZMYLKDB *)getLKDBHelper{
    static ZMYLKDB *my;
    @synchronized(self) {
        if(!my){
            my = [[ZMYLKDB alloc]init];
        }
    }
    return my;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        lkdb = [LKDBHelper getUsingLKDBHelper];
    }
    return self;
}
#pragma mark - 清空数据库，并创建新表
-(void)removeAllTableData{
    [lkdb dropAllTable];
//    [self creatTable];
    
}
#pragma mark - 创建表
//-(void)creatTable{
    /*
    BOOL ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[Book class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[BookRack class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[MyVIPBook class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[MyFavorBook class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[BookInfo class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[ThemeComment class]];
    ret = [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[ReplyComment class]];
     */
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[Book class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[BookRack class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[MyVIPBook class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[MyFavorBook class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[BookInfo class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[LikeComment class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[ThemeComment class]];
//    [[ZMYLKDB getUsingLKDBHelper]getTableCreatedWithClass:[ReplyComment class]];
//    [[ZMYLKDB getUsingLKDBHelper]createTableWithModelClass:[Activity class]];
    
//}
#pragma mark - 更新活动
-(void)updateActivity:(Activity *)newActivity{
    Activity *activity = [Activity searchSingleWithWhere:[NSString stringWithFormat:@"activityid='%@' AND position='%@'",newActivity.activityid,newActivity.position] orderBy:nil];//[lkdb searchSingle:[Activity class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid] orderBy:nil];
    if (activity) {
        [activity upDateNew:newActivity];
        [Activity updateToDB:activity where:[NSString stringWithFormat:@"activityid='%@' AND position='%@'",newActivity.activityid,newActivity.position]];
//        [activity upDateNew:bookRack];
//        [lkdb updateToDB:book where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid]];
    } else {
        [Activity insertToDB:newActivity];
    }
}
#pragma mark 获取某个位置的活动
-(NSArray *)getActivityWithPosition:(NSString *)position{
    return [Activity searchWithWhere:[NSString stringWithFormat:@"position='%@'",position] orderBy:@"is_sticky desc ,time desc" offset:0 count:100];
}
#pragma mark 清空某个位置的活动
-(void)clearActivityWithPosition:(NSString *)position{
    [Activity deleteWithWhere:[NSString stringWithFormat:@"position='%@'",position]];
}
#pragma mark - 更新书籍详情
-(void)updateBook:(Book *)book{
    Book *book1 = [lkdb searchSingle:[Book class] where:[NSString stringWithFormat:@"articleid='%@'",book.articleid] orderBy:nil];
    if (book1) {
        [book1 upDateNew:book];
        [Book updateToDB:book1 where:[NSString stringWithFormat:@"articleid='%@'",book1.articleid]];
    } else {
        [lkdb insertToDB:book];
    }
}
#pragma mark - 添加书架
-(void)insertBookRack:(BookRack *)bookRack{
    TaskList *taskList = [TaskList currentAccount];
    Task *task = taskList.taskArray[2];
    if (!task.isFinshed) {
        task.isFinshed = YES;
        [TaskList saveAccount:taskList];
    }
    NSArray *array = [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"uid='%@'",bookRack.uid] orderBy:@"sortid desc" offset:0 count:500];
    [[ZMYNetWorkAPI default] addBookRackArticleid:bookRack.articleid response:^(NSDictionary *resultDic) {
    } error:^(NSString *errorStr) {
    }];
    if (array.count>0) {
        bookRack.sortid = ((BookRack *)[array objectAtIndex:0]).sortid+1;
    }else{
        bookRack.sortid = 0;
    }
    [lkdb insertToDB:bookRack];
    /*
     BOOL ret = [lkdb insertToDB:bookRack];
    if (ret) {
        [[ZMYNetWorkAPI default]getBookChapterBook:bookRack.book Response:^(NSDictionary *resultDic) {
            NSMutableArray *chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                                       stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",bookRack.articleid]]];
            NSMutableString *chapterIDs = [NSMutableString new];
            NSMutableArray *freeChapter = [NSMutableArray new];
            for (BookChapterInfo *chapterInfo in chapterArray) {
                if (![chapterInfo.is_vip isEqualToString:@"0"]) {
                    break;
                }
                [freeChapter addObject:chapterInfo];
                if ([chapterArray indexOfObject:chapterInfo]==0) {
                    [chapterIDs appendString:chapterInfo.chapterId];
                } else {
                    [chapterIDs appendFormat:@",%@",chapterInfo.chapterId];
                }
                if (freeChapter.count>9) {
                    break;
                }
            }
            if (freeChapter.count>0) {
                NSString *purviewMark = [[NSString stringWithFormat:@"%@%@",((BookChapterInfo *)[freeChapter objectAtIndex:0]).chapterId,((BookChapterInfo *)[freeChapter lastObject]).chapterId] md5];
                purviewMark = [[NSString stringWithFormat:@"qy_%@",purviewMark] md5];
                [[ZMYNetWorkAPI default]downloadChapterTextStr:chapterIDs purviewMark:purviewMark Response:^(NSDictionary *resultDic) {
                    
                } error:^(NSString *errorStr) {
                    
                }];
            }
            
        } error:^(NSString *errorStr) {
            
        }];
        
    }
     */
}
#pragma mark 移除书架
-(void)removeBookRack:(BookRack *)bookRack{
    bookRack = [lkdb searchSingle:[BookRack class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid] orderBy:nil];
    [lkdb deleteToDB:bookRack];
    [[ZMYNetWorkAPI default] removeBookRackArticleid:bookRack.articleid response:^(NSDictionary *resultDic) {
    } error:^(NSString *errorStr) {
    }];
    NSArray *array = [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"sortid>'%ld' AND uid='%@'",(long)bookRack.sortid,bookRack.uid] orderBy:@"sortid asc" offset:0 count:500];
    for (BookRack *book in array) {
        book.sortid = book.sortid-1;
        [lkdb updateToDB:book where:nil callback:nil];
    }
    [self deleteReadSchedule:bookRack.articleid];
}
#pragma mark 更新书架
-(void)updateBookRack:(BookRack *)bookRack{
    BookRack *book = [lkdb searchSingle:[BookRack class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid] orderBy:nil];
    if (book) {
        [book upDateNew:bookRack];
        [BookRack updateToDB:book where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid]];
    } else {
        [self insertBookRack:bookRack];
    }
}
#pragma mark 获取书架
-(NSArray *)getBookRack{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取书架
        return [lkdb search:[BookRack class] where:@"uid='love'" orderBy:@"sortid asc" offset:0 count:500];
    }else{
        //已注册用户
        return [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:@"sortid asc" offset:0 count:500];
    }
    
}
#pragma mark 获取一本书是否在当前用户的书架
-(BOOL)getBookRack:(Book *)book{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取书架
        BookRack *bookRack = [lkdb searchSingle:[BookRack class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='love'",book.articleid] orderBy:nil];
        if (bookRack) {
            return YES;
        } else {
            return NO;
        }
    }else{
        //已注册用户
        BookRack *bookRack = [lkdb searchSingle:[BookRack class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",book.articleid,user.uid] orderBy:nil];
        if (bookRack) {
            return YES;
        } else {
            return NO;
        }
    }
    
}
#pragma mark 将uid='love'的图书添加到当前用户书架
-(NSArray *)addLoveBookRack{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length>0) {
        [lkdb updateToDB:[BookRack class] set:[NSString stringWithFormat:@"uid='%@'",user.uid] where:@"uid='love'"];
        NSArray *array = [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:@"sortid asc" offset:0 count:500];
        for (BookRack *book in array) {
            [[ZMYNetWorkAPI default] addBookRackArticleid:book.articleid response:^(NSDictionary *resultDic) {
            } error:^(NSString *errorStr) {
            }];
        }
        return array;
    }
    return nil;
}
#pragma mark 书架排序
-(void)changeBookRackFrom:(NSInteger)fromItem to:(NSInteger)toItem{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户
        user = [UserAccount new];
        user.uid = @"love";
    }
    BookRack *book = [lkdb searchSingle:[BookRack class] where:[NSString stringWithFormat:@"sortid='%ld' AND uid='%@'",(long)fromItem,user.uid] orderBy:nil];
    if (book) {
        [lkdb deleteToDB:book];
        if (fromItem>toItem) {
            NSArray *array = [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"sortid>'%@' AND sortid<'%@' AND uid='%@'",[NSNumber numberWithInteger:toItem-1],[NSNumber numberWithInteger:fromItem],user.uid] orderBy:@"sortid asc" offset:0 count:500];
            for (BookRack *bookRack in array) {
                bookRack.sortid = bookRack.sortid+1;
                [lkdb updateToDB:bookRack where:nil callback:nil];
            }
            book.sortid = toItem;
            [lkdb insertWhenNotExists:book callback:nil];
        } else {
            NSArray *array = [lkdb search:[BookRack class] where:[NSString stringWithFormat:@"sortid>'%@' AND sortid<'%@' AND uid='%@'",[NSNumber numberWithInteger:fromItem],[NSNumber numberWithInteger:toItem+1],user.uid] orderBy:@"sortid asc" offset:0 count:500];
            for (BookRack *bookRack in array) {
                bookRack.sortid = bookRack.sortid-1;
                [lkdb updateToDB:bookRack where:nil callback:nil];
            }
            book.sortid = toItem;
            [lkdb insertWhenNotExists:book callback:nil];
        }
        
    }
}
#pragma mark - 更新已订阅数据库
-(void)updateMyVIPBook:(MyVIPBook *)bookRack{
    MyVIPBook *book = [lkdb searchSingle:[MyVIPBook class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid] orderBy:nil];
    if (book) {
        [book upDateNew:bookRack];
        [lkdb updateToDB:book where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid]];
    } else {
        [lkdb insertToDB:bookRack];
    }
}
#pragma mark 获取已订阅图书
-(NSArray *)getMyVIPBookPage:(NSInteger)page{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return nil;
    }else{
        //已注册用户
        if (page<1) {
            return nil;
        }
        return [lkdb search:[MyVIPBook class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:@"payTime desc" offset:(int)(page-1)*10 count:10];
    }
}
#pragma mark 获取本地数据库我的订阅图书数量
-(int)getMyVIPBookCount{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return 0;
    }else{
        //已注册用户
        return [lkdb rowCount:[MyVIPBook class] where:[NSString stringWithFormat:@"uid='%@'",user.uid]];
    }
}
#pragma mark 清空已购的图书表
-(void)clearMyVIPBook{
    [lkdb dropTableWithClass:[MyVIPBook class]];
}
#pragma mark - 更新收藏数据库
-(void)updateMyFavorBook:(MyFavorBook *)bookRack{
    MyFavorBook *book = [lkdb searchSingle:[MyFavorBook class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid] orderBy:nil];
    if (book) {
        [book upDateNew:bookRack];
        [lkdb updateToDB:book where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",bookRack.articleid,bookRack.uid]];
    } else {
        [lkdb insertToDB:bookRack];
    }
}
#pragma mark 判断是否收藏了一本书
-(BOOL)isHadFavorTheBook:(Book *)favorBook{
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        return NO;
    }
    MyFavorBook *book = [lkdb searchSingle:[MyFavorBook class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",favorBook.articleid,user.uid] orderBy:nil];
    if (book) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark 获取收藏的图书
-(NSArray *)getMyFavorBook{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return nil;
    }else{
        //已注册用户
        return [lkdb search:[MyFavorBook class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:nil offset:0 count:500];
    }
    
}
#pragma mark 移除一本收藏的图书
-(void)deleteMyFavorBook:(MyFavorBook *)favorBook{
    [lkdb deleteWithClass:[MyFavorBook class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",favorBook.articleid,favorBook.uid]];
}
#pragma mark 清空收藏的图书表
-(void)clearMyFavorBook{
    [lkdb dropTableWithClass:[MyFavorBook class]];
}

#pragma mark - 更新充值记录
-(void)updateRechargeRecord:(RechargeRecord *)rechargeRecord{
    RechargeRecord *recharge = [lkdb searchSingle:[RechargeRecord class] where:[NSString stringWithFormat:@"rechargeRecordID='%@' AND uid='%@'",rechargeRecord.rechargeRecordID,rechargeRecord.uid] orderBy:nil];
    if (recharge) {
        [lkdb updateToDB:rechargeRecord where:[NSString stringWithFormat:@"rechargeRecordID='%@' AND uid='%@'",rechargeRecord.rechargeRecordID,rechargeRecord.uid]];
    } else {
        [lkdb insertToDB:rechargeRecord];
    }
}
#pragma mark 获取充值记录
-(NSArray *)getRechargeRecordPage:(NSInteger)page{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return nil;
    }else{
        //已注册用户
        if (page<1) {
            return nil;
        }
        return [lkdb search:[RechargeRecord class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:@"time desc" offset:(int)(page-1)*10 count:10];
    }
}
#pragma mark 获取未同步的充值记录
-(NSInteger)getRechargeRecord{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return 0;
    }else{
        //已注册用户
        return [lkdb search:[RechargeRecord class] where:[NSString stringWithFormat:@"uid='%@' AND uid='%d'",user.uid,NO] orderBy:nil offset:0 count:500].count;
    }
    
}
#pragma mark - 更新书籍详情
-(void)updateBookInfo:(BookInfo *)book{
    BookInfo *book1 = [lkdb searchSingle:[BookInfo class] where:[NSString stringWithFormat:@"articleid='%@'",book.articleid] orderBy:nil];
    if (book1) {
        [book1 upDateNew:book];
        [lkdb updateToDB:book1 where:[NSString stringWithFormat:@"articleid='%@'",book1.articleid]];
    } else {
        [lkdb insertToDB:book];
    }
}
#pragma mark 获取书籍详情
-(BookInfo *)getBookInfo:(NSString *)articleid{
    BookInfo *book = [[lkdb search:[BookInfo class] where:[NSString stringWithFormat:@"articleid='%@'",articleid] orderBy:nil offset:0 count:500] lastObject];
    return book;
}
#pragma mark - 更新点赞状态
-(void)updateIsLike:(LikeComment *)newLike{
    LikeComment *like = [lkdb searchSingle:[LikeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",newLike.articleid,newLike.commentid,newLike.uid] orderBy:nil];
    if (like) {
        like.isLike = newLike.isLike;
        [lkdb updateToDB:like where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",newLike.articleid,newLike.commentid,newLike.uid]];
    } else {
        [lkdb insertToDB:newLike];
    }
}
#pragma mark 获取目前点赞状态
-(BOOL)getIsLike:(LikeComment *)newLike{
    LikeComment *like = [[lkdb search:[LikeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",newLike.articleid,newLike.commentid,newLike.uid] orderBy:nil offset:0 count:500] lastObject];
    if (like) {
        return like.isLike;
    } else {
        return NO;
    }
    
}
#pragma mark 获取是否点过赞,有的话不请求点赞接口
-(BOOL)getIsLikeOnce:(LikeComment *)newLike{
    LikeComment *like = [[lkdb search:[LikeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",newLike.articleid,newLike.commentid,newLike.uid] orderBy:nil offset:0 count:500] lastObject];
    if (like) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark - 更新书评主题数据库
-(void)updateThemeComment:(ThemeComment *)myComment{
    if (myComment.commentid.length<1) {
        return;
    }
    ThemeComment *comment = [lkdb searchSingle:[ThemeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",myComment.articleid,myComment.commentid,myComment.uid] orderBy:nil];
    if (comment) {
        [comment upDateNew:myComment];
        [lkdb updateToDB:comment where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND uid='%@'",myComment.articleid,myComment.commentid,myComment.uid]];
    } else {
        [lkdb insertToDB:myComment];
    }
}
#pragma mark 根据作品ID获取书评主题
-(NSArray *)getThemeCommentWith:(NSString *)articleid{
    return [lkdb search:[ThemeComment class] where:[NSString stringWithFormat:@"articleid='%@'",articleid] orderBy:@"time desc" offset:0 count:10];
}
#pragma mark 清空书评主题
-(void)clearThemeCommentDBWith:(NSString *)articleid{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        [lkdb deleteWithClass:[ThemeComment class] where:[NSString stringWithFormat:@"articleid='%@'",articleid]];
    }else{
        //已注册用户
        [lkdb deleteWithClass:[ThemeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND uid!='%@'",articleid,user.uid]];
    }
}
#pragma mark 获取本地数据库我的书评
-(NSArray *)getMyCommentPage:(NSInteger)page{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return nil;
    }else{
        //已注册用户
        if (page<1) {
            return nil;
        }
        return [lkdb search:[ThemeComment class] where:[NSString stringWithFormat:@"uid='%@'",user.uid] orderBy:@"time desc" offset:((int)page-1)*10 count:500];
    }
}
#pragma mark 获取本地数据库某一本书我的书评
-(NSArray *)getMyCommentBook:(Book *)book Page:(NSInteger)page{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return nil;
    }else{
        //已注册用户
        if (page<1) {
            return nil;
        }
        return [lkdb search:[ThemeComment class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",book.articleid,user.uid] orderBy:@"time desc" offset:((int)page-1)*10 count:500];
    }
}
#pragma mark 获取本地数据库我的书评的数量
-(int)getMyCommentCount{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return 0;
    }else{
        //已注册用户
        return [lkdb rowCount:[ThemeComment class] where:[NSString stringWithFormat:@"uid='%@'",user.uid]];
    }
}
#pragma mark 清空我的书评
-(void)clearMyCommentDB{
    UserAccount *user = [UserAccount currentAccount];
    if (user.uid.length<1) {
        //未注册用户获取已订阅图书
        return;
    }else{
        //已注册用户
        [lkdb deleteWithClass:[ThemeComment class] where:[NSString stringWithFormat:@"uid='%@'",user.uid]];
    }
}
#pragma mark - 更新回复
-(void)updateReplyComment:(ReplyComment *)myComment{
    if (myComment.commentsid.length<1) {
        return;
    }
    ReplyComment *comment = [lkdb searchSingle:[ReplyComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND commentsid='%@'",myComment.articleid,myComment.commentid,myComment.commentsid] orderBy:nil];
    if (comment) {
        [comment upDateNew:myComment];
        [lkdb updateToDB:comment where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@' AND commentsid='%@'",myComment.articleid,myComment.commentid,myComment.commentsid]];
    } else {
        [lkdb insertToDB:myComment];
    }
}
#pragma mark 根据主题评论获取书评的回复
-(NSArray *)getReplyCommentWith:(ThemeComment *)themeComment{
    return [lkdb search:[ReplyComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@'",themeComment.articleid,themeComment.commentid] orderBy:@"time desc" offset:0 count:10];
}
#pragma mark 清空书评主题
-(void)clearReplyCommentDBWith:(ThemeComment *)themeComment{
    [lkdb deleteWithClass:[ReplyComment class] where:[NSString stringWithFormat:@"articleid='%@' AND commentid='%@'",themeComment.articleid,themeComment.commentid]];
}

#pragma mark - 更新书籍章节的名字和内容，如果没有则插入
-(void)updateBookChapterText:(BookChapterText *)bookChapterText{
    if (bookChapterText.articleid.length<1||bookChapterText.chapterId.length<1) {
        return;
    }
    BookChapterText *comment = [BookChapterText searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@'",bookChapterText.articleid,bookChapterText.chapterId] orderBy:nil];
    if (comment) {
        [BookChapterText updateToDBWithSet:[NSString stringWithFormat:@"chapterName='%@' AND chapterTextString='%@'",bookChapterText.chapterName,bookChapterText.chapterTextString] where:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@'",bookChapterText.articleid,bookChapterText.chapterId]];
    } else {
        [BookChapterText insertToDB:bookChapterText];
    }
}
#pragma mark 解析下载到的章节文件
-(BOOL)unarchiveFreeChapter:(NSString *)downloadFilePath Book:(Book *)book{
    NSString *articleid = book.articleid;
    NSString *textFile  = [[NSString alloc] initWithContentsOfFile:downloadFilePath encoding:NSUTF8StringEncoding error:nil];
    NSMutableArray *array = [[textFile componentsSeparatedByString:@"#nan#wu#ou#ni#tou#fo###"] mutableCopy];
//    NSRange nanRang=[textFile rangeOfString:@"#nan#wu#ou#ni#tou#fo###"];
    if (array.count<1) {//||textFile.length<200||nanRang.length==0
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        if ([fileManager fileExistsAtPath:downloadFilePath]) {
            [fileManager removeItemAtPath:downloadFilePath error:nil];
        }
        return NO;
    }
    NSString *str = array[0];
    if (str.length<1) {
        [array removeObjectAtIndex:0];
    }
    for (NSString *text in array) {
        NSArray *textArray = [text componentsSeparatedByString:@"#Om#Ma#Ni#Be#Me#Hum###"];
        NSString *chapterId = [textArray objectAtIndex:0];
        NSRange rang=[[textArray lastObject] rangeOfString:@"\n"];
        NSString *title = [[textArray lastObject] substringToIndex:rang.location];
        NSString *texts = [[textArray lastObject] substringFromIndex:rang.location+rang.length];
        if (title.length<1||([texts hasSuffix:@"更多精彩作品尽在被窝阅读！###"]?texts.length<80:texts.length<20)) {
            NSFileManager *fileManager = [[NSFileManager alloc] init];
            if ([fileManager fileExistsAtPath:downloadFilePath]) {
                [fileManager removeItemAtPath:downloadFilePath error:nil];
            }
            return NO;
        }
        BookChapterText *chapterText = [BookChapterText new];
        chapterText.articleid = articleid;
        chapterText.chapterName = title;
        chapterText.chapterTextString = texts;
        chapterText.chapterId = chapterId;
        [self updateBookChapterText:chapterText];
    }
    return YES;
}
#pragma mark 根据articleid和chapterId获取章节内容
-(BookChapterText *)getBookChapterTextWithArticleid:(NSString *)articleid chapterId:(NSString *)chapterId{
    return [BookChapterText searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@'",articleid,chapterId] orderBy:nil];
}
#pragma mark 根据articleid判断是否有下载
-(BOOL)getBookChapterTextWithArticleid:(NSString *)articleid{
     BookChapterText *comment = [BookChapterText searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@'",articleid] orderBy:nil];
    if (comment) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark - 更新阅读进度
-(void)updateReadSchedule:(ReadSchedule *)readSchedule{
    UserAccount *user = [UserAccount currentAccount];
    NSString *uid = @"love";
    if (user) {
        uid = user.uid;
    }
    ReadSchedule *readSchedule1 = [lkdb searchSingle:[ReadSchedule class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",readSchedule.articleid,uid] orderBy:nil];
    if (readSchedule1) {
//        [lkdb updateToDB:readSchedule where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",readSchedule.articleid,uid]];
        [lkdb updateToDB:[ReadSchedule class] set:[NSString stringWithFormat:@"chapterId='%@',rang='%@'",readSchedule.chapterId,readSchedule.rang] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",readSchedule.articleid,uid]];
    } else {
        [lkdb insertToDB:readSchedule];
    }
}
#pragma mark 删除阅读进度
-(void)deleteReadSchedule:(NSString *)articleid{
    UserAccount *user = [UserAccount currentAccount];
    NSString *uid = @"love";
    if (user) {
        uid = user.uid;
    }
    ReadSchedule *readSchedule1 = [lkdb searchSingle:[ReadSchedule class] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@'",articleid,uid] orderBy:nil];
    if (readSchedule1) {
        [lkdb deleteToDB:readSchedule1];
    }
}
#pragma mark 获取阅读进度
-(ReadSchedule *)getReadSchedule:(NSString *)articleid{
    UserAccount *user = [UserAccount currentAccount];
    NSString *uid = @"love";
    if (user) {
        uid = user.uid;
    }
    ReadSchedule *readSchedule = [ReadSchedule searchSingleWithWhere:[NSString stringWithFormat:@"uid='%@' AND articleid='%@'",uid,articleid] orderBy:nil];
    if (!readSchedule) {
        NSMutableArray *chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                                   stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",articleid]]];
        if (chapterArray.count<1) {
            return nil;
        }
        readSchedule = [ReadSchedule new];
        readSchedule.articleid = articleid;
        readSchedule.rang = NSStringFromRange(NSMakeRange(0, 10));
        BookChapterInfo *chapterInfo = [chapterArray objectAtIndex:0];
        readSchedule.chapterId = chapterInfo.chapterId;
        [lkdb insertToDB:readSchedule];
    }
    return readSchedule;
}
#pragma mark - 添加书签
-(void)insertToBookmarkDB:(Bookmark *)bookmark{

    Bookmark *readSchedule1 = [Bookmark searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@' AND rang='%@'",bookmark.articleid,bookmark.chapterId,bookmark.rang] orderBy:nil];
    if (!readSchedule1) {
        [lkdb insertToDB:bookmark];
    }
}
#pragma mark 删除书签
-(void)deleteToBookmarkDB:(Bookmark *)bookmark{
    
    Bookmark *readSchedule1 = [Bookmark searchSingleWithWhere:bookmark orderBy:nil];
    if (readSchedule1) {
        [lkdb deleteToDB:bookmark];
    }
}
#pragma mark 根据作品ID获取书签
-(NSArray *)getBookmarkArticleid:(NSString *)articleid{
    return [lkdb search:[Bookmark class] where:[NSString stringWithFormat:@"articleid='%@'",articleid] orderBy:@"chapterId desc" offset:0 count:200];
}
#pragma mark 根据章节ID获取书签
-(NSArray *)getBookmarkChapterId:(NSString *)chapterId{
    return [lkdb search:[Bookmark class] where:[NSString stringWithFormat:@"chapterId='%@'",chapterId] orderBy:nil offset:0 count:200];
}
#pragma mark - 添加高亮
-(void)insertToHighlightMarkDB:(HighlightMark *)highlightMark{
    
    HighlightMark *readSchedule1 = [HighlightMark searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@' AND rang='%@'",highlightMark.articleid,highlightMark.chapterId,highlightMark.rang] orderBy:nil];
    if (!readSchedule1) {
        [lkdb insertToDB:highlightMark];
    }
}
#pragma mark 删除高亮
-(void)deleteToHighlightMarkDB:(HighlightMark *)highlightMark{
    
    HighlightMark *readSchedule1 = [HighlightMark searchSingleWithWhere:highlightMark orderBy:nil];
    if (readSchedule1) {
        [lkdb deleteToDB:highlightMark];
    }
}
#pragma mark 根据作品ID获取高亮
-(NSArray *)getHighlightMarkArticleid:(NSString *)articleid{
    return [lkdb search:[HighlightMark class] where:[NSString stringWithFormat:@"articleid='%@'",articleid] orderBy:@"chapterId desc" offset:0 count:200];
}
#pragma mark 根据章节ID获取高亮
-(NSArray *)getHighlightMarkChapterId:(NSString *)chapterId{
    return [lkdb search:[HighlightMark class] where:[NSString stringWithFormat:@"chapterId='%@'",chapterId] orderBy:nil offset:0 count:200];
}
#pragma mark - 添加笔记
-(void)insertToBookNoteDB:(BookNote *)highlightMark{
    
    BookNote *readSchedule1 = [BookNote searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND chapterId='%@' AND rang='%@'",highlightMark.articleid,highlightMark.chapterId,highlightMark.rang] orderBy:nil];
    if (!readSchedule1) {
        [lkdb insertToDB:highlightMark];
    }
}
#pragma mark 删除笔记
-(void)deleteToBookNoteDB:(BookNote *)highlightMark{
    
    BookNote *readSchedule1 = [BookNote searchSingleWithWhere:highlightMark orderBy:nil];
    if (readSchedule1) {
        [lkdb deleteToDB:highlightMark];
    }
}
#pragma mark 根据章节ID获取笔记
-(NSArray *)getBookNoteChapterId:(NSString *)chapterId{
    return [lkdb search:[BookNote class] where:[NSString stringWithFormat:@"chapterId='%@'",chapterId] orderBy:nil offset:0 count:200];
}
@end
